#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/1/16 18:46
# @Author  : leon yan
# @Site    :
# @File    : Monitor.py
# @Software: PyCharm
import datetime
import json
import sys

import lib.xinjePlc_Alarm as rdAlarm

from PyQt5.QtCore import pyqtSlot, QDir, QStringListModel, Qt
from PyQt5.QtWidgets import (QApplication, QMainWindow, QAbstractItemView, QGridLayout, QMessageBox)
from loguru import logger

import Globalist as gl
import lib.applets as sApp
from OneHeight import QOneHeight
from UserLogin import QUserLogin
from lib.qChartDrawing import QChartDrawing
from lib.fileprocess import cfgProcess
from resource.Monitor_ui import Ui_Form


DEFAULT_STYLE = """
QProgressBar{
    border: 2px solid grey;
    border-radius: 5px;
    text-align: center
}

QProgressBar::chunk {
    background-color: lightblue;
    width: 10px;
    margin: 1px;
}
"""

ALARM_STYLE = """
QProgressBar{
    border: 1px solid grey;
    border-radius: 1px;
    text-align: center
}

QProgressBar::chunk {
    background-color: #d57e8a;
    width: 10px;
    margin: 0px;
}
"""

# 浏览目录文件
def exploreDirFiles(sour, fileSuffix=None):
    if sour:
        dirObj = QDir(sour)  # 若sous为空，则使用其当前目录
        aa = dirObj.entryList(QDir.Files)
        ''''''
        if fileSuffix:
            aa2 = []
            for i in range(len(aa)):
                if fileSuffix in aa[i]:
                    aa2.append(aa[i])
            aa3 = aa2
        else:
            aa3 = aa
        if (aa3 is []) or (aa3 is None):
            return None
        else:
            return aa3
    else:
        return None


def Write2Plc1(bSignalList):
    # start stop
    for i in range(17):
        if i != 9 and i != 14:
            gl.global_var["send_plc_pool"][str(i)].append([i, [700, bSignalList]])
        # else:
        #     gl.global_var["send_plc_pool"][str(i)].append(i, [10000, bSignalList])


def Write2Plc2(bSignalList):
    # reset
    for i in range(17):
        if i != 9 and i != 14:
            gl.global_var["send_plc_pool"][str(i)].append([121, bSignalList])
        # else:
        #     gl.global_var["send_plc_pool"][str(i)].append(i, [10000, bSignalList])


class QMonitor(QMainWindow, Ui_Form):
    def __init__(self, parent=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)  # self.lineTable.frame.setVisible(False)  # 本表无操作按钮
        self.setupUi(self)
        self.CurrentTime = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
        ''''''
        self.label_3.setText(gl.global_var["deviceName"])
        '''启动更新方法'''
        self.threadObj = gl.get_value("obj_UpdateThread")
        self.threadObj.bPulse.connect(self.do_UpdateStatus)
        self.bMainPulse = 0
        ''''''
        self.model = QStringListModel(self)
        self.listDeviceView.setEditTriggers(QAbstractItemView.NoEditTriggers)
        aa = []
        for key, value in gl.global_var["deviceDict"].items():
            aa.append(value[0] + "_" + value[1])
        self.model.setStringList(aa)
        self.listDeviceView.setModel(self.model)
        '''机器代码显示'''
        i = 0
        for key, value in gl.global_var["deviceDict"].items():
            if i < gl.global_var["deviceNum"]:
                self.sortLayout.setTextDict(value[0], i)
            i += 1

        '''Pie chart'''
        self.QChartDrawing = QChartDrawing()
        self.draw_pieChart()
        self.draw_barChart()
        self.draw_barChart2()

        ''''''
        logger.info("monitor start")
        ''''''
        self.testCounter = 0

    def __del__(self):
        print("Monitor is deleted")

    @pyqtSlot()
    def draw_pieChart(self):  # 绘制饼图
        chart = self.chartViewPie.chart()  # 获取chart对象
        self.QChartDrawing.draw_pieChart(chart)

    @pyqtSlot()
    def draw_barChart(self):  # 绘制柱状图 日产量监控
        chart = self.chartViewBar1.chart()  # 获取chart对象
        self.QChartDrawing.draw_barChart(chart)

    @pyqtSlot()
    def draw_barChart2(self):  # 绘制柱状图 日功耗监控
        chart = self.chartViewBar2.chart()  # 获取chart对象
        self.QChartDrawing.draw_barChart2(chart, False)

    @pyqtSlot()
    def do_UpdateStatus(self):
        # print(gl.global_var["send_plc_pool"]["0"])
        """"""
        aa = gl.global_var["monitorVar"]
        self.labCurSpeed.setText(str(aa["CurSpeed"]))
        self.labCurVelocity.setText(str(aa["CurVelocity"]))
        self.labTodayAmount.setText(str(aa["TodayAmount"]))
        self.labTodayPower.setText(str(aa["TodayPower"]))
        self.labTotalAmount.setText(str(aa["TotalAmount"]))
        self.labTotalPower.setText(str(aa["TotalPower"]))
        self.labPowerTime.setText(str(sApp.second2time(aa["PowerTime"])))
        self.labWorkTime.setText(str(sApp.second2time(aa["WorkTime"])))
        self.labAlarmTime.setText(str(sApp.second2time(aa["AlarmTime"])))
        ''''''
        statusVar = gl.global_var["statusVar"]
        eValue = statusVar["eSystemStatus"]
        labValue = statusVar["aSystemStatusLabel"]
        self.labStatus.setText(labValue[str(eValue)])
        self.labAlarm.setEnabled(statusVar["bAlarm"])
        self.labReady.setEnabled(statusVar["bReady"])
        self.labRunning.setEnabled(statusVar["bRunning"])
        self.labLink.setEnabled(statusVar["bConnected"])
        self.labMaintain.setEnabled(statusVar["bMaintainReminder"])
        if gl.global_var["statusVar"]["eSystemStatus"] == 1:
            statusVar["bReady"] = 1
        else:
            statusVar["bReady"] = 0
        if gl.global_var["statusVar"]["eSystemStatus"] == 3:
            statusVar["bAlarm"] = 1
        else:
            statusVar["bAlarm"] = 0

        gl.global_var["statusVar"]["bConnected"] = 1
        for k, v in gl.global_var["deviceIpDict"].items():
            if v[1] == 0:
                gl.global_var["statusVar"]["bConnected"] = 0
                break

        if gl.global_var["operateVar"]["bLineOn"]:
            self.btnLineOn.setText("联机中")
            aa = "background-color: rgb(221, 255, 189);font: 75 12pt '3ds';color: rgb(0, 0, 127);"
            self.btnLineOn.setStyleSheet(aa)
            if gl.global_var["statusVar"]["eSystemStatus"] != 2 and gl.global_var["statusVar"]["eSystemStatus"] != 3:
                gl.global_var["statusVar"]["eSystemStatus"] = 1
        else:
            self.btnLineOn.setText("未联机...")
            aa = "background-color: rgb(235, 235, 235);"
            self.btnLineOn.setStyleSheet(aa)
            gl.global_var["statusVar"]["eSystemStatus"] = 0

        ''''''
        technologyVar = gl.global_var["technology"]
        self.labTechnology.setText(technologyVar["curTechnology"])
        self.labMaterial.setText(technologyVar["curMaterial"])
        self.lineBarcode.setText(technologyVar["curBarcode"])
        self.labDescriptions.setText(technologyVar["curDescriptions"])
        '''维护监控'''
        curMaintainVar = gl.global_var["chartMonitor"]["curMaintainVar"]
        for i in range(len(curMaintainVar)):
            exec("self.progressBar_" + str(i + 1) + ".setValue(" + str(curMaintainVar[i]) + ")")
            exec("self.progressBar_" + str(i + 1) + ".setStyleSheet(ALARM_STYLE)")

        '''急停，运行显示'''
        bEmergencyList = gl.global_var["bEmergencyStopList"]
        bAlarmList = gl.global_var["bAlarmList"]
        bRunningList = gl.global_var["bRunningList"]
        emergencyDict = {}
        alarm_run_statusDict = {}
        for i in range(gl.global_var["deviceNum"]):
            emergencyDict[i] = bEmergencyList[i]
            aa = 0
            if bAlarmList[i]:
                aa = 2
            elif bRunningList[i]:
                aa = 1
            alarm_run_statusDict[i] = aa
        self.sortLayout.setLayoutDict(alarm_run_statusDict)
        self.sortLayout.setMarkerEmergencyDict(emergencyDict)
        ''''''
        if 1 in bAlarmList:
            gl.global_var["statusVar"]["bAlarm"] = 1
        else:
            gl.global_var["statusVar"]["bAlarm"] = 0

        if 0 in bRunningList:
            gl.global_var["statusVar"]["bRunning"] = 0
        else:
            gl.global_var["statusVar"]["bRunning"] = 1

        """报警"""
        j = 0
        self.labAlarmInfo.clear()
        alarmInfo = rdAlarm.rdPlcAlarm()
        for i in range(len(alarmInfo)):
            if alarmInfo[i]:
                self.labAlarmInfo.addItem(str(alarmInfo[i]), j)
                j += 1
        ''''''
        '''机器监控'''
        ''''''
        '''
        机器监控
        1, 设定显示连接状态
        '''
        self.sortLayout.setLinkDict(gl.global_var["deviceDict"])
        ''''''
        '''设定值'''
        gl.global_var["operateVar"]["lineVelocitySet"] = self.lineVelocitySet.value()
        # print(gl.global_var["deviceIpDict"])

    '''slot 信号--PushButton'''
    @pyqtSlot()
    def on_btnLineOn_clicked(self):
        if gl.global_var["statusVar"]["bRunning"] == 1:
            QMessageBox.warning(self, "警告", "运行中不可切换!")
            return
        if gl.global_var["operateVar"]["bLineOn"] == 1:
            gl.global_var["operateVar"]["bLineOn"] = 0
        else:
            gl.global_var["operateVar"]["bLineOn"] = 1

    @pyqtSlot()
    def on_btnOneSet_pressed(self):
        if gl.global_var["statusVar"]["eSystemStatus"] == 2 or gl.global_var["statusVar"]["eSystemStatus"] == 0:
            QMessageBox.warning(self, "警告", "运行中或未联机时，不可进行一键设定!")
            return
        gl.global_var["operateVar"]["bOneSet"] = 1

    @pyqtSlot()
    def on_btnOneSet_released(self):
        gl.global_var["operateVar"]["bOneSet"] = 0

    '''启动'''

    @pyqtSlot()
    def on_btnOneStart_pressed(self):
        if gl.global_var["operateVar"]["bLineOn"] == 0 or gl.global_var["statusVar"]["eSystemStatus"] != 1:
            QMessageBox.warning(self, "警告", "未联机或系统未准备好!")
            return
        ret = QMessageBox.question(self, "提醒", "确定要一键启动吗?\n请注意观察周边环境!")
        if ret != QMessageBox.Yes:
            return
        gl.global_var["operateVar"]["bOneStart"] = 1
        gl.global_var["statusVar"]["eSystemStatus"] = 2
        # Write2Plc1([1, 0])

    @pyqtSlot()
    def on_btnOneStart_released(self):
        gl.global_var["operateVar"]["bOneStart"] = 0
        # Write2Plc1([0, 0])

    '''暂停'''

    @pyqtSlot()
    def on_btnOneStop_pressed(self):
        gl.global_var["operateVar"]["bOneStop"] = 1
        if gl.global_var["statusVar"]["eSystemStatus"] != 3:
            gl.global_var["statusVar"]["eSystemStatus"] = 1
        Write2Plc1([0, 1])

    @pyqtSlot()
    def on_btnOneStop_released(self):
        gl.global_var["operateVar"]["bOneStop"] = 0
        Write2Plc1([0, 0])

    '''复位'''

    @pyqtSlot()
    def on_btnReset_pressed(self):
        gl.global_var["operateVar"]["bReset"] = 1

    @pyqtSlot()
    def on_btnReset_released(self):
        gl.global_var["operateVar"]["bReset"] = 0

    @pyqtSlot()
    def on_btnOneHeight_clicked(self):
        if gl.global_var["userVar"]["LoginUser"] == '':
            QMessageBox.warning(self, "警告", "请先登入")
            return
        formDoc = QOneHeight(self)  # 必须传递self，否则无法显示
        formDoc.setAttribute(Qt.WA_DeleteOnClose)
        formDoc.setWindowFlag(Qt.Window, True)

        formDoc.setWindowModality(Qt.WindowModal)
        formDoc.setWindowFlag(Qt.CustomizeWindowHint, True)
        formDoc.setWindowFlag(Qt.WindowMinMaxButtonsHint, False)
        formDoc.setWindowFlag(Qt.WindowCloseButtonHint, True)
        formDoc.setWindowFlag(Qt.WindowStaysOnTopHint, True)

        formDoc.setWindowOpacity(1.0)  # 窗口透明度
        formDoc.show()

    @pyqtSlot()
    def on_btnLogin_clicked(self):
        if gl.global_var["userVar"]["LoginUser"] != '':
            return
        formDoc = QUserLogin(self)  # 必须传递self，否则无法显示
        formDoc.setAttribute(Qt.WA_DeleteOnClose)
        formDoc.setWindowFlag(Qt.Window, True)

        formDoc.setWindowModality(Qt.WindowModal)
        formDoc.setWindowFlag(Qt.CustomizeWindowHint, True)
        formDoc.setWindowFlag(Qt.WindowMinMaxButtonsHint, False)
        formDoc.setWindowFlag(Qt.WindowCloseButtonHint, True)
        formDoc.setWindowFlag(Qt.WindowStaysOnTopHint, True)

        formDoc.setWindowOpacity(1.0)  # 窗口透明度
        formDoc.show()

    @pyqtSlot()
    def on_btnLogout_clicked(self):
        if gl.global_var["userVar"]["LoginUser"] == '':
            return
        gl.global_var["userVar"]["Admin"] = 0
        gl.global_var["userVar"]["LoginUser"] = ""
        gl.global_var["userVar"]["LoginUserName"] = ""
        gl.global_var["userVar"]["LoginStatus"] = "未登入"
        QMessageBox.information(self, "提示", "注销成功")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    objWindow = QMonitor()
    objWindow.show()
    sys.exit(app.exec_())
